package com.zzty.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DBUtilPool {
    static PropertyUtil props=new PropertyUtil();
    private static final String driver=props.getProp().getProperty("driver");
    private static final String url=props.getProp().getProperty("url");
    private static final String userName=props.getProp().getProperty("userName");
    private static final String password=props.getProp().getProperty("password");
    private static final int poolSize=Integer.valueOf(props.getProp().getProperty("pool.size"));
    private static final List<Connection> connections=new ArrayList<Connection>();
    private static PreparedStatement pst=null;

    // 加载驱动
    static {
        try {
            Class.forName(driver);
            for (int i=0; i < poolSize; i++) {
                connections.add(DriverManager.getConnection(url, userName, password));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 创建连接
    public static Connection getConnection() throws Exception {
        Connection cn=null;
        if (connections.size() > 0) {
            cn=connections.get(0);
            connections.remove(0);
        } else {
            for (int i=0; i < poolSize; i++) {
                cn=DriverManager.getConnection(url, userName, password);
                connections.add(cn);
            }
        }
        return cn;
    }

    public static void releaseConnection(Connection cn) {
        if(connections.size()<=poolSize){
            connections.add(cn);
        }else{
            try{
                cn.close();
            }catch (Exception ex){
                ex.printStackTrace();
            }

        }

    }


}
